<template>
  <div class="write-article-container">
    <!-- <NavBar /> -->
    <el-card class="write-article-card">
      <h2 class="page-title">article</h2>
      <el-form :model="form" label-width="100px" class="article-form" size="large">
        <el-row :gutter="32">
          <el-col :span="19">
            <el-form-item label="标题" required>
              <el-input v-model="form.title" placeholder="请输入文章标题" />
            </el-form-item>
            <el-form-item label="正文" required>
              <div style="width: 100%;">
                  <v-md-editor v-model="form.body" ref="mdEditor" height="700px"></v-md-editor>
              </div>
            </el-form-item>

          </el-col>
          <el-col :span="5">
            <el-form-item label="显示目录">
              <el-checkbox v-model="form.show_toc">显示富文本TOC目录</el-checkbox>
            </el-form-item>
            <el-form-item label="发布时间">
              <el-date-picker v-model="form.pub_time" type="datetime" value-format="YYYY-MM-DD HH:mm:ss" placeholder="选择发布时间" style="width: 100%;" />
            </el-form-item>
            <el-form-item label="文章状态">
              <el-select v-model="form.status" placeholder="请选择">
                <el-option label="发表" value="p" />
                <el-option label="草稿" value="d" />
              </el-select>
            </el-form-item>
            <el-form-item label="评论状态">
              <el-select v-model="form.comment_status" placeholder="请选择">
                <el-option label="打开" value="o" />
                <el-option label="关闭" value="c" />
              </el-select>
            </el-form-item>
            <el-form-item label="作者">
              <el-input v-if="current_status === 'create'" disabled v-model="form.author_username" placeholder="请输入作者名" />
              <el-input v-else v-model="form.author_username" disabled placeholder="请输入作者名" />
            </el-form-item>
            <el-form-item label="排序">
              <el-input-number v-model="form.article_order" :min="0" :max="9999" />
            </el-form-item>
            <el-form-item label="分类">
              <el-select ref="categorySelectRef" v-model="form.category_id" @visible-change="handleCategorySelectVisibleChange" :filter-method="handleCategoryFilter" filterable placeholder="请选择分类" :loading="isLoading">
                <el-option v-for="cat in categorise_list" :key="cat.id" :label="cat.name" :value="cat.id" />
              </el-select>
            <CreateCategory @created="getCategoryList" :parentCategoryList="categorise_list" />
            <UpdateCategory v-if="current_status === 'edit'" @updated="getCategoryList" :category="form.category_detail"/>

            </el-form-item>
            <el-form-item label="标签">
              <el-select ref="tagSelectRef" @visible-change="handleTagSelectVisibleChange" :debounce="500" :filter-method="handleTagFilter" v-model="form.tag_ids" filterable multiple placeholder="请选择标签" :loading="isLoading">
                <el-option v-for="tag in tag_list" :key="tag.id" :label="tag.name" :value="tag.id" />
              </el-select>
              <CreateTag @created="() => getTagList(true)" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-form-item v-if="current_status === 'create'">
          <el-button type="primary" @click="handleCreateArticle">发布</el-button>
          <el-button @click="handleSaveDraft">保存草稿</el-button>
        </el-form-item>
        <el-form-item v-if="current_status === 'edit'">
          <el-button type="primary" @click="handleUpdateArticle">保存</el-button>
          <el-button @click="handleSaveDraft">保存草稿</el-button>
        </el-form-item>
      </el-form>
    </el-card>
  </div>
</template>

<script setup>
import { ref, onMounted, onUnmounted, nextTick,watch } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import blogApi from '../api/blog.js';
// import NavBar from '@/components/NavBar.vue'
import { useUserStore } from "../stores/user";
import fileServerApi from "../api/fileServer.js";
import CreateCategory from '../components/CreateCategory.vue'
import UpdateCategory from '../components/UpdateCategory.vue'
import CreateTag from '../components/CreateTag.vue';
import { useTabStore } from "../stores/tab.js";

const tabStore = useTabStore()
const current_status = ref('create')
const userStore = useUserStore();


const categorise_list = ref([]);
const tag_list = ref([]);
const route = useRoute();
const router = useRouter();

const mdEditor = ref(null);

const form = ref({
  id : 0,
  title: '',
  body: '',
  pub_time: new Date(),
  status: 'p',
  comment_status: 'o',
  type: "a",
  author_id: 0,
  author_username: '',
  article_order: 0,
  show_toc: false,
  category_id: '',
  category_name: '',
  category_detail: {},
  tag_ids: []
});

// tags
const searchTagName = ref('');
const tagCurrentPage = ref(1);
const tagPageSize = ref(10);
const tagTotal = ref(0);
const isLoading = ref(false);
const tagHasMore = ref(true);
const tagSelectRef = ref(null);
const handleTagFilter = (keyword) => {
  // 当关键词变化时触发API搜索
  searchTagName.value = keyword;
  // getTagList(true); // 重置分页并搜索
};

// categories
const categorySearchName = ref('');
const categoryCurrentPage = ref(1);
const categoryPageSize = ref(10);
const categoryTotal = ref(0);
const categoryHasMore = ref(true);
const categorySelectRef = ref(null);
const handleCategoryFilter = (keyword) => {
  categorySearchName.value = keyword;
};

function initForm() {
  form.value.author_username = userStore.state.username;
  form.value.author_id = userStore.state.user_id;
};

async function handleCreateArticle() {
  console.log("创建文章", form.value)
  const res = await blogApi.CreateArticle(form.value);
  console.log("创建文章", res);
  if (res.code === 0) {
    ElMessage.success('创建成功');
  }
}

async function handleUpdateArticle() {
  // TODO: 发布逻辑
  console.log('发布-edit', form.value)
  const res = await blogApi.UpdateArticle(form.value);
  console.log("更新文章", res);
  if (res.code === 0) {
    ElMessage.success('更新成功');
  }
}
function handleSaveDraft() {
  form.value.status = 'draft'
  // TODO: 保存草稿逻辑
  console.log('保存草稿', form.value)
}

const getArticleDetail = async (id) => {
  const res = await blogApi.GetArticleDetailWithTagDetail(id);
  if (res.code === 0) {
    form.value = {
      ...form.value,
      ...res.data,
      tag_ids: res.data.tags.map(tag => tag.id)
    };
    tag_list.value.push(...res.data.tags);
    categorise_list.value.push(res.data.category_detail)
  }
};

const getCategoryList = async (isReset = false) => {

  if (isLoading.value) return;

  if (isReset) {
    categoryCurrentPage.value = 1;
    categoryHasMore.value = true;
    categorise_list.value = [];
    categoryTotal.value = 0;
  }

  // 没有更多数据， 停止请求
  if (!categoryHasMore.value) return;
  isLoading.value = true;

  const res = await blogApi.GetCategoryList(categoryPageSize.value, (categoryCurrentPage.value - 1) * categoryPageSize.value, categorySearchName.value);
  if (res.code === 0) {
    if (categoryCurrentPage == 1){
      categorise_list.value = res.data.list;
    }else {
      categorise_list.value = [...categorise_list.value, ...res.data.list];
      categoryTotal.value = res.data.total;
    }
    categoryHasMore.value = categorise_list.value.length < res.data.total;
    categoryCurrentPage.value++;
  }
  isLoading.value = false;
};

const getTagList = async (isReset = false) => {
  if (isLoading.value) return;
  
  // 重置分页
  if (isReset){
    tagCurrentPage.value = 1;
    tagHasMore.value = true;
    tag_list.value = [];
    tagTotal.value = 0;
  }

  // 没有更多数据， 停止请求
  if (!tagHasMore.value) return;

  isLoading.value = true;

  const res = await blogApi.GetTagList(tagPageSize.value, (tagCurrentPage.value - 1) * tagPageSize.value, searchTagName.value);
  if (res.code === 0) {
    tagTotal.value = res.data.total;
    tagHasMore.value = tag_list.value.length < res.data.total;
    if (tagCurrentPage.value === 1){
      tag_list.value = res.data.list || [];
    } else{
      tag_list.value = [...tag_list.value, ...res.data.list];
    }
    console.log('标签加载状态', { currentPage: tagCurrentPage.value, total: tagTotal.value, loaded: tag_list.value.length, hasMore: tagHasMore.value });
    tagCurrentPage.value++;
  }
  isLoading.value = false;
};

// 添加防抖函数
const debounce = (fn, delay = 300) => {
  let timer = null;
  return (...args) => {
    if (timer) clearTimeout(timer);
    timer = setTimeout(() => {
      fn.apply(this, args);
    }, delay);
  }
}

// 防抖处理搜索
const debouncedTagSearch = debounce(()=> {
  getTagList(true);
}, 500)

const debouncedCategorySearch = debounce(()=> {
  getCategoryList(true)
}, 500)


const getAuthorInfo = async () => {
  const res = await blogApi.GetAuthorInfo();
  if (res.code === 0) {
    form.value.author_id = res.data.id;
    form.value.author_username = res.data.username;
  }
};

// 上传文件
const edImageUpload = async (file) => {
  if (file.size > 2 * 1024 * 1024) {
    ElMessage.error('图片大小超过 2MB');  // 使用 Element Plus 提示
    return;
  }
  const formData = new FormData();
  formData.append('file', file, 'upload.png');
  const res = await fileServerApi.imageUpload(formData);
  if (res.url) {
    const imageUrl = res.url;
    copyToClickBoard(imageUrl);
  } else {
    ElMessage.error('图片上传失败');
  }
}

// 插入内容到文本编辑器(主要是copy图片)
const copyToClickBoard = (content) => {
  const markdown = `![](${content})`;
  const editorElement = mdEditor.value?.$el?.querySelector('textarea');
  if (editorElement) {
    const startPos = editorElement.selectionStart;
    const endPos = editorElement.selectionEnd;
    const currentValue = form.value.body;
    
    form.value.body = currentValue.substring(0, startPos) + 
                   markdown + 
                   currentValue.substring(endPos);
    
    nextTick(() => {
      editorElement.selectionStart = startPos + markdown.length;
      editorElement.selectionEnd = startPos + markdown.length;
      editorElement.focus();
    });
  }

};

// 粘贴事件处理（限制在编辑器区域）
const handlePaste = (e) => {
  const clipboardData = e.clipboardData || window.clipboardData;
  if (!clipboardData) return;

  // 检查是否在 v-md-editor 区域内粘贴（通过类名判断）
  const isEditorArea = e.target.closest('.v-md-editor');
  if (!isEditorArea) return;

  // 提取图片文件
  const items = clipboardData.items;
  let blob = null;
  for (let i = 0; i < items.length; i++) {
    if (items[i].type.indexOf('image') !== -1) {
      blob = items[i].getAsFile();
      break;
    }
  }
  if (blob) edImageUpload(blob);
};

// 滚动分页加载处理
const handleTagScroll = (e) => {
  const target = e.target;
  const { scrollTop, scrollHeight, clientHeight } = target;
  if (scrollTop + clientHeight >= scrollHeight - 20 && tagHasMore.value && !isLoading.value) {
    getTagList();
  }
}

const handleCategoryScroll = (e) => {
  const target = e.target;
  const { scrollTop, scrollHeight, clientHeight } = target;
  if (scrollTop + clientHeight >= scrollHeight - 20 && tagHasMore.value && !isLoading.value) {
    getCategoryList();
  }
}

// 监听tag搜索框
watch(searchTagName, (newVal)=> {
  debouncedTagSearch();
})

watch(categorySearchName, (newVal) => {
  debouncedCategorySearch();
})

// 监听tag下拉滚动
const handleCategorySelectVisibleChange = (visible) => {
  
  if (visible && categorySelectRef.value) {
    nextTick(() => {
      console.log(categorySelectRef.value);
      const popper = categorySelectRef.value.popperRef;
      if (!popper) {
        return;
      }
      // 监听内容区的滚动
      const wrap = popper.querySelector('.el-select-dropdown__wrap');
      if (!wrap) {
        return;
      }
      wrap.removeEventListener('scroll', handleCategoryScroll);
      wrap.addEventListener('scroll', handleCategoryScroll);
    });

  } else if (categorySelectRef.value) {
    const popper = categorySelectRef.value.popperRef;
    if (popper) {
      const wrap = popper.querySelector('.el-select-dropdown__wrap');
      if (wrap) {
        wrap.removeEventListener('scroll', handleCategoryScroll);
    }
  }
  }
}
const handleTagSelectVisibleChange = (visible) => {
  
  if (visible && tagSelectRef.value) {
    nextTick(() => {
      console.log(tagSelectRef.value);
      const popper = tagSelectRef.value.popperRef;
      if (!popper) {
        return;
      }
      // 监听内容区的滚动
      const wrap = popper.querySelector('.el-select-dropdown__wrap');
      if (!wrap) {
        return;
      }
      wrap.removeEventListener('scroll', handleTagScroll);
      wrap.addEventListener('scroll', handleTagScroll);
      console.log('滚动事件已绑定');
      console.log('绑定');
    });

  } else if (tagSelectRef.value) {
    const popper = tagSelectRef.value.popperRef;
    if (popper) {
      const wrap = popper.querySelector('.el-select-dropdown__wrap');
      if (wrap) {
        wrap.removeEventListener('scroll', handleTagScroll);
    }
  }
  }
}

onMounted(async () => {
  await getCategoryList();
  await getTagList(true);
  tabStore.setPageName(route.name)
  // await getAuthorInfo();
  document.addEventListener('paste', handlePaste);

  // 编辑文章
  if (route.params.id) {
    current_status.value = 'edit'
    console.log(current_status.value);
    
    const id = parseInt(route.params.id, 10);
    form.value.id = id;
    await getArticleDetail(id);
  } else {
    initForm();
  }
});


onUnmounted(() => {
  document.removeEventListener('paste', handlePaste);
});

</script>

<style scoped>
.write-article-container {
  margin: 32px;
}
.write-article-card {
  padding: 2px 31px 2px 2px;
}
.page-title {
  margin-bottom: 24px;
  font-size: 28px;
  font-weight: bold;
  text-align: left;
}
.article-form {
  margin-top: 8px;
}
</style>